package com.lgh.hotel.handler.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.lgh.hotel.dao.pojo.SysUser;
import com.lgh.hotel.service.SysUserService;
import com.lgh.hotel.utils.JWTUtils;
import com.lgh.hotel.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SuccessHandler implements AuthenticationSuccessHandler {

    RedisTemplate<String,String> redisTemplate;

    public SuccessHandler(RedisTemplate<String, String> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    SysUserService sysUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        String name = authentication.getName();
        //得到当前登录成功用户的用户名 生成jwttoken
        String token = JWTUtils.createToken(name);
        log.info("登录成功，生成token:{}",token);
        SysUser userByUsername = sysUserService.findUserByUsername(name);
        this.redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(userByUsername),1,TimeUnit.DAYS);
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        writer.write(JSONObject.toJSONString(Result.succ(map)));
        writer.flush();
        writer.close();
    }
}
